/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TrabUpPanel.java
 *
 * Created on 04/12/2011, 13:27:58
 */
package proj5labbd.graphics.trabalho;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class TrabUpPanel extends OperationPanel {

    /** Creates new form TrabUpPanel */
    public TrabUpPanel(TrabFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbUpdate.addActionListener(new TrabAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbUpdate = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbUpdate = new javax.swing.JTable();
        jpnParam2 = new javax.swing.JPanel();
        jlbInicio2 = new javax.swing.JLabel();
        jlbFim2 = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        jtbDepartamento = new javax.swing.JTable();
        jlbDepartamento2 = new javax.swing.JLabel();
        jlbFuncionario2 = new javax.swing.JLabel();
        jScrollPane7 = new javax.swing.JScrollPane();
        jtbFuncionario = new javax.swing.JTable();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Atualização"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jbUpdate.setText("Atualizar");

        jtbUpdate.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbUpdate);

        jpnParam2.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de busca"));

        jlbInicio2.setText("Início");

        jlbFim2.setText("Fim");

        jtbDepartamento.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane6.setViewportView(jtbDepartamento);

        jlbDepartamento2.setText("Departamento");

        jlbFuncionario2.setText("Funcionário");

        jtbFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane7.setViewportView(jtbFuncionario);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParam2Layout = new javax.swing.GroupLayout(jpnParam2);
        jpnParam2.setLayout(jpnParam2Layout);
        jpnParam2Layout.setHorizontalGroup(
            jpnParam2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParam2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParam2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParam2Layout.createSequentialGroup()
                        .addComponent(jScrollPane6, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(jpnParam2Layout.createSequentialGroup()
                        .addComponent(jlbInicio2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(54, 54, 54)
                        .addComponent(jlbFim2)
                        .addGap(352, 352, 352))
                    .addGroup(jpnParam2Layout.createSequentialGroup()
                        .addComponent(jlbDepartamento2)
                        .addContainerGap(380, Short.MAX_VALUE))
                    .addGroup(jpnParam2Layout.createSequentialGroup()
                        .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParam2Layout.createSequentialGroup()
                        .addGroup(jpnParam2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 483, Short.MAX_VALUE)
                            .addGroup(jpnParam2Layout.createSequentialGroup()
                                .addComponent(jlbFuncionario2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 402, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())))
        );
        jpnParam2Layout.setVerticalGroup(
            jpnParam2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParam2Layout.createSequentialGroup()
                .addGroup(jpnParam2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbInicio2)
                    .addComponent(jlbFim2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParam2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbDepartamento2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbFuncionario2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jpnParam2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jbUpdate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jpnParam2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbUpdate))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Método para pegar os dados das tabelas a serem exibidas e colocá-los nas JTables
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar os dados das tabelas");
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Controla os eventos de clique do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbDepartamento.clearSelection();
        jtbFuncionario.clearSelection();
        jtbUpdate.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JButton jbUpdate;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbDepartamento2;
    private javax.swing.JLabel jlbFim2;
    private javax.swing.JLabel jlbFuncionario2;
    private javax.swing.JLabel jlbInicio2;
    private javax.swing.JPanel jpnParam2;
    private javax.swing.JTable jtbDepartamento;
    private javax.swing.JTable jtbFuncionario;
    private javax.swing.JTable jtbUpdate;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata as tabelas funcionario, departamento e trabalho
     */
   private void setupTable() throws SQLException {
        
        String [] titlesFu = {"ID","Nome","Data de nascimento","CPF",
            "Salario","Cargo"};
        String [] fieldsFu = {"funcionario.idFu","funcionario.nomeCompletoFu","funcionario.dataNascimentoFu",
            "funcionario.cpfFu","funcionario.salarioFu","tipoFuncionario.descricaoTipoFu"};
        String [] paramsFu = {"tipoFuncionario.idTipoFu=funcionario.idTipoFu"};
        String [][] sFu = dbInterface.view(fieldsFu, paramsFu, new String[]{"funcionario","tipoFuncionario"});
        
        DefaultTableModel model = new DefaultTableModel(sFu,titlesFu);
        jtbFuncionario.setModel(model);
        
        String [] titlesDe = {"ID","Nome","Telefone","CNPJ da emissora",
            "Nome da emissora","Nro. de funcionários"};
        String [] fieldsDe = {"departamento.idDe","departamento.nomeDe","departamento.telefoneDe",
            "departamento.cnpjEm","emissora.nomeCompletoEm","departamento.nroFuncionariosDe"};
        String [] paramsDe = {"departamento.cnpjEm=emissora.cnpjEm"};
        String [][] sDe = dbInterface.view(fieldsDe, paramsDe, new String[]{"departamento","emissora"});
        
        model = new DefaultTableModel(sDe,titlesDe);
        jtbDepartamento.setModel(model);
        
        String [] fieldsTr = {"departamento.idDe","departamento.nomeDe","funcionario.idFu",
            "funcionario.nomeCompletoFu","trabalho.dataInicioTr","trabalho.dataFimTr"
        };
        String [] titlesTr = {"ID do departamento","Nome do departamento","ID do funcionário",
            "Nome do funcionário","Data de início","Data de fim"
        };
        String [] paramsTr = {
            "departamento.idDe=trabalho.idDe","funcionario.idFu=trabalho.idFu"
        };
        
        String [][] sTr = dbInterface.view(fieldsTr, paramsTr, new String[]{"trabalho","departamento","funcionario"});
        
        model = new DefaultTableModel(sTr,titlesTr);
        jtbUpdate.setModel(model);
        
    }
    
    class TrabAction implements ActionListener {
        
        /*
         * Controla os eventos da atualização
         */
        public void actionPerformed(ActionEvent e) {
            
            ArrayList<String> fields = new ArrayList<String>();
            
            if (jtbDepartamento.getSelectedRowCount() == 1) {
                fields.add("trabalho.idDe="+jtbDepartamento.getValueAt(jtbDepartamento.getSelectedRow(), 0));
            }
            
            if (jtbFuncionario.getSelectedRowCount() == 1) {
                fields.add("trabalho.idFu="+jtbFuncionario.getValueAt(jtbFuncionario.getSelectedRow(), 0));
            }
            
            if (jftxtIni.getText().compareTo("  -  -    ") != 0) {
                fields.add("trabalho.dataInicioTr=TO_DATE('"+jftxtIni.getText()+"','DD-MM-YYYY')");
            }
            
            if (jftxtFim.getText().compareTo("  -  -    ") != 0) {
                fields.add("trabalho.dataFimTr=TO_DATE('"+jftxtFim.getText()+"','DD-MM-YYYY')");
            }
            
            if (fields.size() > 0 && jtbUpdate.getSelectedRowCount() > 0) {
                String [] params = new String[3];
                String [] fieldsArray = new String[fields.size()];
                fields.toArray(fieldsArray);
                int [] rows = jtbUpdate.getSelectedRows();
                for ( int i = 0; i < rows.length; i++ ) {
                    try {
                        params[0] = "trabalho.idFu="+jtbUpdate.getValueAt(rows[i],2).toString();
                        params[1] = "trabalho.idDe='"+jtbUpdate.getValueAt(rows[i],0).toString()+"'";
                        params[2] = "trabalho.dataInicioTr"
                                + "=TO_DATE('"+jtbUpdate.getValueAt(rows[i], 4).toString().substring(0, 10) +
                                "','YYYY-MM-DD')";
                        dbInterface.update(fieldsArray, params,
                                new String[]{"trabalho"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Não foi possível "
                                + "atualizar os dados da " + rows[i] + "linha no banco.");
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você deve selecionar os "
                        + "registros a serem modificados e inserir nos campos as modificações");
            }
            
            jtbUpdate.clearSelection();
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }
            
        }
    }

}
